package com.hrm.interceptor;

import com.hrm.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;
    //前置拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 前后端分离有时候会有两次请求，第一次为OPTIONS请求，默认会拦截所有请求。
         */
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            return true;
        }

        String token = request.getHeader("Authorization");
        //System.out.println("Authorization:"+token);
        if(token==null){
            throw new Exception("无权访问");
        }
        try{
            //解析token
            Claims claims = jwtUtil.parseJWT(token);
            //获取员工的角色信息
            Object roles = claims.get("roles");
            //获取员工的id
            String id = claims.getId();


            //获取员工的loginname
            String loginname = claims.getSubject();
            System.out.println("id:"+id+"\t:loginname:"+loginname+"\troles:"+roles);

            request.getSession().setAttribute("roles",roles);


        }catch (Exception e){
            throw new Exception("无效的token");
        }


        return true;
    }
}
